/*
 * SqStack.c
 *
 *  Created on: 2011-12-1
 *      Author: tracl01
 */

#include <stdlib.h>
#include <stdio.h>
#define STACK_LIST_SIZE		100
#define STACK_INCREMENT		10
typedef int Elemtype;
typedef struct {
	Elemtype *top;
	Elemtype *base;
	int stacksize;
}SqStack;

int initStack(SqStack *S){	//初始化时传递一个此结构体的指针来即可，可以给我传递一未初始化的地址，但不能
	S->base = (Elemtype *)malloc(STACK_LIST_SIZE*sizeof(Elemtype));//传递未初始化的指针
	if (!S->base) {
		exit(EXIT_FAILURE);
	}
	S->top = S->base;
	S->stacksize = STACK_LIST_SIZE;
	return EXIT_SUCCESS;
}

int stackEmpty(SqStack S){
	if (S.base == S.top) {
		return EXIT_SUCCESS;
	} else {
		return EXIT_FAILURE;
	}
}

int getTop(SqStack S, Elemtype *e){
	if (S.base == S.top) {
		return EXIT_FAILURE;
	} else {
		*e = *(S.top-1);			//这里尤其要注意，e是一个指针，
		return EXIT_SUCCESS;
	}
}

int push(SqStack *S, Elemtype e){
	if ((S->top - S->base) >= S->stacksize) {
		S->base = (Elemtype *)realloc(S->base,
				(S->stacksize + STACK_INCREMENT)*sizeof(Elemtype));
		S->top = S->base + S->stacksize;	//重新赋予地址
		S->stacksize += STACK_INCREMENT;
	} else {
		*S->top++ = e;
	}
	return EXIT_SUCCESS;
}

int pop(SqStack *S, Elemtype *e){
	if (S->base == S->top) {
		return EXIT_FAILURE;
	}
	*e = *(--S->top);				//注意这里的书写，*在--前面
	return EXIT_SUCCESS;
}
/*
int main(void){
	SqStack S;
	Elemtype e;
	if(!initStack(&S))
		printf("init success\n");			//好有意思啊！
	int i;
	for (i = 1; i < 20; ++i) {
		push(&S, i);
		pop(&S, &e);
		printf("%d ",e);
	}
	return EXIT_SUCCESS;
}
*/
